//
//  GBInterMaster_Launcher.m
//  NetworkTest
//
//  Created by xiaosi on 16/7/26.
//  Copyright © 2016年 xiaosi. All rights reserved.
//

#import "GBInterMaster_Launcher.h"

@implementation GBInterMaster_Launcher

@synthesize host;
@synthesize port;
@synthesize socket;

@synthesize aesKey;
@synthesize serverConnID;
@synthesize localConnID;
@synthesize registerTag;
@synthesize currentWindow;
@synthesize loginUser;



- (void )requestReceive:(NSNotification* )notification{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    int res = 0x00;
    NSDictionary * result = userInfo;
    int cmd = [[result objectForKey:@"cmd"] intValue];
    int cmdType = [[result objectForKey:@"cmdType"] intValue];
    int msgNumber = [result objectForKey:@"msgNumber"] == nil?0:[[result objectForKey:@"msgNumber"] intValue];
    int dataVersion = [result objectForKey:@"dataVersion"] == nil?0x02:[[result objectForKey:@"dataVersion"] intValue];
    if(cmdType == PTCP_V10_VALUE_CMD_TYPE_APP_SYSTEM){
        if(cmd == LOGIC_APP_CMD_USERREGISTERVEGISTER){//用户注册（获取验证码）
            if([result objectForKey:@"userAccount"] != nil){
                NSString* userAccount = [result objectForKey:@"userAccount"];
                res = [GBInterMaster_APPLogic requestUserRegisterVegister:msgNumber withAccount:userAccount withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_USERREGISTER){//用户注册
            if([result objectForKey:@"userPwd"] == nil){
                return;
            }
            if([result objectForKey:@"checkCode"] == nil){
                return;
            }
            NSString* userPwd = [result objectForKey:@"userPwd"];
            NSString* checkCode = [result objectForKey:@"checkCode"];
            res = [GBInterMaster_APPLogic requestUserRegister:msgNumber withPassword:userPwd withCheckCode:checkCode withService:self];
        }else if(cmd == LOGIC_APP_CMD_RESETPWDVEGISTER){//忘记密码（获取验证码）
            if([result objectForKey:@"userAccount"] != nil){
                NSString* userAccount = [result objectForKey:@"userAccount"];
                res = [GBInterMaster_APPLogic requestUserForgetPwdVegister:msgNumber withAccount:userAccount withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_RESETPWD){//忘记密码（验证校验码）
            if([result objectForKey:@"checkCode"] != nil){
                NSString* checkCode = [result objectForKey:@"checkCode"];
                res = [GBInterMaster_APPLogic requestUserForgetPwd:msgNumber withCheckCode:checkCode withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_RESETPWDNEW){//忘记密码（设置新密码）
            if([result objectForKey:@"userPwd"] != nil){
                NSString* userPwd = [result objectForKey:@"userPwd"];
                res = [GBInterMaster_APPLogic requestUserNewPwd:msgNumber withPassword:userPwd withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_LOGIN){//用户登录
            if([result objectForKey:@"userAccount"] == nil){
                return;
            }
            if([result objectForKey:@"userPwd"] == nil){
                return;
            }
            NSString* checkCode = @"000000";
            if([result objectForKey:@"checkCode"] != nil){
                checkCode = [result objectForKey:@"checkCode"];
            }
            NSString* userAccount = [result objectForKey:@"userAccount"];
            NSString* userPwd = [result objectForKey:@"userPwd"];
            self.loginUser.account = userAccount;
            self.loginUser.loginPassword = userPwd;
            self.loginUser.checkCode = checkCode;
            res = [GBInterMaster_APPLogic requestLogin:msgNumber withUserInfo:self.loginUser withService:self];
        }else if(cmd == LOGIC_APP_CMD_UPDATEPWD){//修改密码
            if([result objectForKey:@"oldPassword"] == nil){
                return;
            }
            if([result objectForKey:@"newPassword"] == nil){
                return;
            }
            NSString* oldPassword = [result objectForKey:@"oldPassword"];
            NSString* newPassword = [result objectForKey:@"newPassword"];
            res = [GBInterMaster_APPLogic requestUpdatePwd:msgNumber withOldPassword:oldPassword withNewPassword:newPassword withService:self];
        }else if(cmd == LOGIC_APP_CMD_ACCEPTPOSSESSOR){//所有者认证（绑定设备）
            if([result objectForKey:@"deviceKey"] != nil){
                NSString* deviceKey = [result objectForKey:@"deviceKey"];
                res = [GBInterMaster_APPLogic requestAcceptPossessor:msgNumber withDeviceKey:deviceKey withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_UPDATEDEVICEINFO){//修改设备名字
            if([result objectForKey:@"deviceAccount"] == nil){
                return;
            }
            if([result objectForKey:@"deviceName"] == nil){
                return;
            }
            NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
            NSString* deviceName = [result objectForKey:@"deviceName"];
            res = [GBInterMaster_APPLogic requestDeviceRename:msgNumber withDeviceAccount:deviceAccount withDeviceName:deviceName withService:self];
        }else if(cmd == LOGIC_APP_CMD_GETDEVICELIS){//获取设备列表
            res = [GBInterMaster_APPLogic requestDeviceList:msgNumber withService:self];
        }else if(cmd == LOGIC_APP_CMD_DEVICEUSERLIST){//获取设备使用者列表
            if([result objectForKey:@"deviceAccount"] != nil){
                NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
                res = [GBInterMaster_APPLogic requestDeviceUserList:msgNumber withDeviceAccount:deviceAccount withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_REMOVEDEVICE){//解除绑定
            if([result objectForKey:@"deviceAccount"] != nil){
                NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
                res = [GBInterMaster_APPLogic requestRelieveDevice:msgNumber withDeviceAccount:deviceAccount withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_ADDDEVICEUSER){//添加使用者
            if([result objectForKey:@"deviceAccount"] == nil){
                return;
            }
            if([result objectForKey:@"userAccount"] == nil){
                return;
            }
            if([result objectForKey:@"userAlias"] == nil){
                return;
            }
            NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
            NSString* userAccount = [result objectForKey:@"userAccount"];
            NSString* userAlias = [result objectForKey:@"userAlias"];
            res = [GBInterMaster_APPLogic requestAddDeviceUser:msgNumber withDeviceAccount:deviceAccount withUserAccount:userAccount withUserAlias:userAlias withService:self];
        }else if(cmd == LOGIC_APP_CMD_DELETEDEVICEUSER){//删除使用者
            if([result objectForKey:@"deviceAccount"] == nil){
                return;
            }
            if([result objectForKey:@"userAccount"] == nil){
                return;
            }
            NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
            NSString* userAccount = [result objectForKey:@"userAccount"];
            res = [GBInterMaster_APPLogic requestDeleteDeviceUser:msgNumber withDeviceAccount:deviceAccount withUserAccount:userAccount withService:self];
        }else if(cmd == LOGIC_APP_CMD_UPDATEDEVICEUSER){//编辑使用者
            if([result objectForKey:@"deviceAccount"] == nil){
                return;
            }
            if([result objectForKey:@"userAccount"] == nil){
                return;
            }
            if([result objectForKey:@"userAlias"] == nil){
                return;
            }
            NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
            NSString* userAccount = [result objectForKey:@"userAccount"];
            NSString* userAlias = [result objectForKey:@"userAlias"];
            res = [GBInterMaster_APPLogic requestEditDeviceUser:msgNumber withDeviceAccount:deviceAccount withUserAccount:userAccount withUserAlias:userAlias withService:self];
        }else if(cmd == LOGIC_APP_CMD_DEVICEOWNCHANGE){//所有者转移
            if([result objectForKey:@"deviceAccount"] == nil){
                return;
            }
            if([result objectForKey:@"userAccount"] == nil){
                return;
            }
            NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
            NSString* userAccount = [result objectForKey:@"userAccount"];
            res = [GBInterMaster_APPLogic requestDeviceOwnChange:msgNumber withDeviceAccount:deviceAccount withUserAccount:userAccount withService:self];
        }else if(cmd == LOGIC_APP_CMD_GETDEVICECONFIG){//获取设备系统配置
            if([result objectForKey:@"deviceAccount"] != nil){
                NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
                res = [GBInterMaster_APPLogic requestDeviceConfig:msgNumber withDeviceAccount:deviceAccount withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_MSGRECEIVEMODEL){//设置数据同步
            if([result objectForKey:@"deviceAccount"] == nil){
                return;
            }
            if([result objectForKey:@"msgMod"] == nil){
                return;
            }
            NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
            int msgMod = [[result objectForKey:@"msgMod" ] intValue];
            res = [GBInterMaster_APPLogic requestMsgReceiveMode:msgNumber withDeviceAccount:deviceAccount withMsgMode:msgMod withService:self];
        }else if(cmd == LOGIC_APP_CMD_GETDEVICESTATUS){//获取设备最新状态
            if([result objectForKey:@"deviceAccount"] == nil){
                return;
            }
            NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
            int deviceType = [GBInterMaster_Util convert36to10:deviceAccount withLength:3];
            if(deviceType == DEVICE_TYPE_AMPUX_GM8_13001){
                res = [GBInterMaster_APPLogic requestDeviceStatus:msgNumber withDataType:PTCP_V10_DATA_TYPE_SELF withSubId:0 withDeviceAccount:deviceAccount withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_GETDEVICERUNRECORD){//获取设备运行记录
            if([result objectForKey:@"deviceAccount"] == nil){
                return;
            }
            int tag = 0;
            if([result objectForKey:@"tag"] != nil){
                tag = [[result objectForKey:@"tag"] intValue];
            }
            NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
            int deviceType = [GBInterMaster_Util convert36to10:deviceAccount withLength:3];
            if(deviceType == DEVICE_TYPE_AMPUX_GM8_13001){
                res = [GBInterMaster_APPLogic requestDeviceRuns:msgNumber withDataType:PTCP_V10_DATA_TYPE_SELF withSubId:0 withTag:tag withDeviceAccount:deviceAccount withService:self];
            }
        }else if(cmd == LOGIC_APP_CMD_GETUSEROPES){//获取用户操作记录
            if([result objectForKey:@"deviceAccount"] == nil){
                return;
            }
            if([result objectForKey:@"userAccount"] == nil){
                return;
            }
            int tag = 0;
            if([result objectForKey:@"tag"] != nil){
                tag = [[result objectForKey:@"tag"] intValue];
            }
            NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
            NSString* userAccount = [result objectForKey:@"userAccount"];
            res = [GBInterMaster_APPLogic requestUserOpes:msgNumber withTag:tag withDeviceAccount:deviceAccount withUserAccount:userAccount withService:self];
            
        }else if(cmd == LOGIC_APP_CMD_GETPROGRAMINFO){//获取设备时段信息
            if([result objectForKey:@"deviceAccount"] != nil){
                NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
                res = [GBInterMaster_APPLogic requestShowProgramInfo:msgNumber withDataType:PTCP_V10_DATA_TYPE_SELF withSubId:0 withDeviceAccount:deviceAccount withService:self];
            }
        }
    }else if(cmdType == PTCP_V10_VALUE_CMD_TYPE_APP_DEVICE){
        if([result objectForKey:@"deviceAccount"] == nil){
            return;
        }
        NSString* deviceAccount = [result objectForKey:@"deviceAccount"];
        int device_type = [GBInterMaster_Util convert36to10:deviceAccount withLength:3];
        
        if(cmd == LOGIC_CMD_REQUEST_POWERSWITCH){//开关机设置
            if([result objectForKey:@"powerSwitch"] == nil){
                return;
            }
            int powerSwitch = [[result objectForKey:@"powerSwitch" ] intValue];
            if(device_type == DEVICE_TYPE_AMPUX_GM8_13001){
                res = [GBInterMaster_DeviceLogic13001 requestPowerSwitch:msgNumber withDataVersion:dataVersion withDeviceAccount:deviceAccount withPowerSwitch:powerSwitch withService:self];
            }
        }else if(cmd == LOGIC_CMD_REQUEST_WORKMODEL){//工作模式
            if([result objectForKey:@"workMode"] == nil){
                return;
            }
            int workMode = [[result objectForKey:@"workMode" ] intValue];
            if(device_type == DEVICE_TYPE_AMPUX_GM8_13001){
                res = [GBInterMaster_DeviceLogic13001 requestWorkMode:msgNumber withDataVersion:dataVersion withDeviceAccount:deviceAccount withWorkMode:workMode withService:self];
            }            
        }else if(cmd == LOGIC_CMD_REQUEST_HEATMODE){//加热模式
            if([result objectForKey:@"heatMode"] == nil){
                return;
            }
            int heatMode = [[result objectForKey:@"heatMode" ] intValue];
            if(device_type == DEVICE_TYPE_AMPUX_GM8_13001){
                res = [GBInterMaster_DeviceLogic13001 requestHeatMode:msgNumber withDataVersion:dataVersion withDeviceAccount:deviceAccount withHeatMode:heatMode withService:self];
            }
        }else if(cmd == LOGIC_CMD_REQUEST_TEMPEHM){//设置温度
            if([result objectForKey:@"heatMode"] == nil){
                return;
            }
            int heatMode = [[result objectForKey:@"heatMode" ] intValue];
            if([result objectForKey:@"tempe"] == nil){
                return;
            }
            short tempe = [[result objectForKey:@"tempe" ] shortValue];
            if(device_type == DEVICE_TYPE_AMPUX_GM8_13001){
                res = [GBInterMaster_DeviceLogic13001 requestSetTempe:msgNumber withDataVersion:dataVersion withDeviceAccount:deviceAccount withHeatMode:heatMode withTempe:tempe withService:self];
            }
        }else if(cmd == LOGIC_CMD_REQUEST_DAYPARTING){//设置时段
            if([result objectForKey:@"program"] == nil){
                return;
            }
            GBInterMaster_Bean_ProgramInfo*  program = [result objectForKey:@"program" ];
            if(device_type == DEVICE_TYPE_AMPUX_GM8_13001){
                res = [GBInterMaster_DeviceLogic13001 requestSetProgram:msgNumber withDataVersion:dataVersion withDeviceAccount:deviceAccount withProgram:program withService:self];
            }
        }
    }else{
        
    }
}


- (id) initWithHost:(NSString*)serverHost withPort:(int)serverPort{
    self = [super init];
    if(self){
        self.host = serverHost;
        self.port = serverPort;
        self.loginUser = [[GBInterMaster_Bean_UserInfo alloc] init];
    }
    return self;
}

- (int) registerNotificationReceiver{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestReceive:) name:NOTIFICATION_REQUEST object:nil];
    return 0x00;
}

- (int) unregisterNotificationReceiver{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    return 0x00;
}

- (int) connectToServer{
    NSError *error = nil;
    NSLog(@"current task");
//    dispatch_get_main_queue()
    dispatch_queue_t queue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//dispatch_get_main_queue
    self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:queue];
    self.socket.delegate = self;
    [self.socket connectToHost:host onPort:port error:&error];
    NSLog(@"connectToServer");
    if(error != nil){
        return -1;
    }else{
        return 0;
    }
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"socket连接成功");
    [[NSNotificationCenter defaultCenter]postNotificationName:@"socketConnectSuccess" object:self userInfo:nil];
    [GBInterMaster_APPLogic connRegister:self];
    [self.socket readDataWithTimeout:-1  tag:1];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(nullable NSError *)err
{
    NSLog(@"sorry the connect is fail");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5* NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"socketConnectFail" object:self userInfo:nil];
            NSError *error = nil;
            [self.socket connectToHost:host onPort:port error:&error];
        });
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    [GBInterMaster_LogicLauncher launching:data withService:self];
    [self.socket readDataWithTimeout:-1 tag:0];
}

@end
